<template>
  <el-dialog v-model="showLoginDialog" title="登录" width="500px">
    <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
      <el-form-item label="账号" prop="userID">
        <el-input v-model="loginForm.userID" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <div class="mb-4">
        <el-button type="primary" @click="submitForm" :disabled="isSubmitting">登录</el-button>
      </div>
      <p v-if="loginErrorMsg" style="color:red;">{{ loginErrorMsg }}</p>
      <p v-if="alreadyLoggedInMsg" style="color:orange;">{{ alreadyLoggedInMsg }}</p>
    </el-form>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, defineComponent } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElDialog } from 'element-plus';

export default defineComponent({
  name: 'Login',
  components: {ElDialog},
  setup() {
    const store = useStore();
    const router = useRouter();
    const loginFormRef = ref(null);
    const loginForm = reactive({
      userID: '',
      password: ''
    });
    const rules = {
      userID: [{required: true, message: '请输入用户名', trigger: 'blur'}],
      password: [{required: true, message: '请输入密码', trigger: 'blur'}]
    };
    const loginErrorMsg = ref('');
    const alreadyLoggedInMsg = ref('');
    const isSubmitting = ref(false);
    const showLoginDialog = computed({
      get: () => store.getters['auth/isLoginDialogVisible'],
      set: (value) => store.commit('auth/TOGGLE_LOGIN_DIALOG', value)
    });

    const isLoggedIn = computed(() => store.getters['auth/isLoggedIn']);

    const submitForm = async () => {
      isSubmitting.value = true;
      loginErrorMsg.value = '';

      try {
        await loginFormRef.value.validate(async (valid) => {
          if (valid) {
            if (!isLoggedIn.value) {
              try {
                await store.dispatch('auth/login', {
                  userID: loginForm.userID,
                  password: loginForm.password
                });
                const redirect = router.currentRoute.value.query.redirect || '/';
                router.push(redirect);
                // 不再需要emit，因为直接管理了Vuex状态
                showLoginDialog.value = false;
              } catch (error) {
                loginErrorMsg.value = error.message || '登录失败，请重试。';
              }
            } else {
              alreadyLoggedInMsg.value = '您已登录，无需重复登录。';
            }
          }
        });
      } catch (validateError) {
        console.error('表单验证出错', validateError);
      } finally {
        isSubmitting.value = false;
      }
    };

    return {
      loginForm,
      rules,
      loginFormRef,
      submitForm,
      loginErrorMsg,
      alreadyLoggedInMsg,
      isSubmitting,
      showLoginDialog
    };
  }
});
</script>

<style scoped>
.mb-4 {
  display: block;
  text-align: center;
  margin-bottom: 1rem;
}
</style>